package netty.common.serializer;

import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

public class UdpDecoder extends MessageToMessageDecoder<DatagramPacket> {

	@Override
	protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
		final byte[] array;
		final int offset;
		final int length = packet.content().readableBytes();
		if (packet.content().hasArray()) {
			array = packet.content().array();
			offset = packet.content().arrayOffset() + packet.content().readerIndex();
		} else {
			array = ByteBufUtil.getBytes(packet.content(), packet.content().readerIndex(), length, false);
			offset = 0;
		}

		com.zetas.option.push.message.sdk.PushSDKMessage.Message4Backend msg =
				com.zetas.option.push.message.sdk.PushSDKMessage.Message4Backend.parseFrom(array);
		out.add(msg);
	}
}
